<?php

namespace App\Services\TransferGoldCash;

use App\Models\User;
use Illuminate\Support\Facades\DB;

class TransferGoldCash
{
    protected User $self;

    protected User $child;

    protected float $cashes = 0;

    protected $payCode = null;

    public function __construct(User $self, User $child, $cashes, $payCode = null)
    {
        $this->self = $self;
        $this->child = $child;
        $this->cashes = $cashes;
        $this->payCode = $payCode;
    }

    protected function transfer()
    {
        DB::transaction(function () {
            $data = ['child_user_id' => $this->child->id];
            account_cashes($this->self)->minusTransferedCashes($this->cashes, $data);

            $data = ['parent_user_id' => $this->self->id];
            account_cashes($this->child)->plusTransferedCashes($this->cashes, $data);
        });
    }

    public function apply()
    {
        if (empty($this->payCode)) return;

        $this->transfer();
    }
}
